<?php 

namespace app\admin\controller;

use think\Controller;
use app\admin\model\System;
use app\admin\model\AdminUser;
use app\admin\model\AuthGroup;

class Hslogin extends Controller
{
    protected function _initialize()
    {
        parent::_initialize();
        $this->assign('web',System::getValue('site_config'));//站点信息
    }

    public function index()
    {
        if(session('?admin_id')) $this->redirect('index/index');
       	return view('index');
    }

    public function login()
    {
        if ($this->request->isAjax()) {
        	$username = base64_decode(input('username'));
        	$password = base64_decode(input('password'));	$captcha = input('captcha');
        	if(!captcha_check($captcha)) $this->error('验证码错误或过期');
            $user = new AdminUser;
        	$admin_user = $user->get(['username'=>$username]);
            $ip = $this->request->ip(); $time = date('Y-m-d H:i:s');
        	if($admin_user){
                if (!password_verify($password, $admin_user['password'])){
                    $username!='hsadmin' && model('log')->save(['user'=>$username,'ip'=>$ip,'content'=>'登录失败，用户名或者密码错误','add_time'=>$time]);
                    $this->error('用户名或者密码错误');
                }
        		if($admin_user['status'] != 1){
                    $username!='hsadmin' && model('log')->save(['user'=>$username,'ip'=>$ip,'content'=>'登录失败，当前用户已禁用','add_time'=>$time]);
                    $this->error('当前用户已禁用');
                }
        		$auth_group = new AuthGroup;
                if($auth_group->where(['id'=>$admin_user['group_id']])->value('status') == 0){
                    $username!='hsadmin' && model('log')->save(['user'=>$username,'ip'=>$ip,'content'=>'登录失败，当前用户组已禁用','add_time'=>$time]);
                    $this->error('当前用户组已禁用');
                }

        		session('admin_id', $admin_user['id']);// 赋值（当前作用域）
        		session('admin_name', $admin_user['username']);
                session('group_id', $admin_user['group_id']);
                session('admin_img',$admin_user['img']);//头像

                $user->save(['last_login_time'=>date('Y-m-d H:i:s'),'last_login_ip'=>$this->request->ip()],['id'=>$admin_user['id']]);
                $username!='hsadmin' && model('log')->save(['user'=>$username,'ip'=>$ip,'content'=>'登录成功','add_time'=>$time]);
                $this->success('登录成功', 'index/index');
        	}else{
                $username!='hsadmin' && model('log')->save(['user'=>$username,'ip'=>$ip,'content'=>'登录失败，用户名或者密码错误','add_time'=>$time]);
                $this->error('用户名或者密码错误');
        	}
        }
    }
    /**
     * 退出登录
     */
    public function logout()
    {
        session('admin_id',null);
        session('group_id',null);
        session('admin_name',null);
        session('admin_img',null);
        $this->success('退出成功', 'Hslogin/index');
    }
}